<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/reimupage/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/reimupage/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/reimupage/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/reimupage/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/reimupage/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/reimupage/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/reimupage/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JavaScript,RegExp," />










<meta name="description" content="正则表达式 笔记 前言本系列为学习过程中知识的整理，学习笔记，资料均来源于网络 正文 正则表达式的创建有两种方式：new RegExp(expression)和直接字面量123456//使用直接字面量创建var exp1 = /pattern/flags;var exp1 = /(^\s+)|(\s+$)/g;//使用RegExp对象创建var exp2 = new RegExp(&apos;pattern">
<meta name="keywords" content="JavaScript,RegExp">
<meta property="og:type" content="article">
<meta property="og:title" content="正则表达式 笔记">
<meta property="og:url" content="http://hatsunem1ku.gitee.io/reimupage/2018/05/06/RegExp对象/index.html">
<meta property="og:site_name" content="Reimu&#39;Blog">
<meta property="og:description" content="正则表达式 笔记 前言本系列为学习过程中知识的整理，学习笔记，资料均来源于网络 正文 正则表达式的创建有两种方式：new RegExp(expression)和直接字面量123456//使用直接字面量创建var exp1 = /pattern/flags;var exp1 = /(^\s+)|(\s+$)/g;//使用RegExp对象创建var exp2 = new RegExp(&apos;pattern">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-05-06T07:49:55.252Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="正则表达式 笔记">
<meta name="twitter:description" content="正则表达式 笔记 前言本系列为学习过程中知识的整理，学习笔记，资料均来源于网络 正文 正则表达式的创建有两种方式：new RegExp(expression)和直接字面量123456//使用直接字面量创建var exp1 = /pattern/flags;var exp1 = /(^\s+)|(\s+$)/g;//使用RegExp对象创建var exp2 = new RegExp(&apos;pattern">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/reimupage/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://hatsunem1ku.gitee.io/reimupage/2018/05/06/RegExp对象/"/>





  <title>正则表达式 笔记 | Reimu'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/reimupage/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Reimu'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">求知若饥 虚心若愚</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/reimupage/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/reimupage/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/reimupage/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/reimupage/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/reimupage/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://hatsunem1ku.gitee.io/reimupage/reimupage/2018/05/06/RegExp对象/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Reimu">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/reimupage/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Reimu'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">正则表达式 笔记</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-06T15:33:33+08:00">
                2018-05-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/reimupage/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="正则表达式-笔记"><a href="#正则表达式-笔记" class="headerlink" title="正则表达式 笔记"></a>正则表达式 笔记</h1><hr>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>本系列为学习过程中知识的整理，学习笔记，资料均来源于网络</p>
<h1 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h1><hr>
<p>正则表达式的创建有两种方式：<strong>new RegExp(expression)</strong>和<strong>直接字面量</strong><br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用直接字面量创建</span></span><br><span class="line"><span class="keyword">var</span> exp1 = <span class="regexp">/pattern/</span>flags;</span><br><span class="line"><span class="keyword">var</span> exp1 = <span class="regexp">/(^\s+)|(\s+$)/g</span>;</span><br><span class="line"><span class="comment">//使用RegExp对象创建</span></span><br><span class="line"><span class="keyword">var</span> exp2 = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">'pattern'</span>,<span class="string">'flags'</span>);</span><br><span class="line"><span class="keyword">var</span> exp2 = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">'(^\\s+)|(\\s+$)'</span>,<span class="string">'g'</span>);</span><br></pre></td></tr></table></figure></p>
<p>每个正则表达式都可带有一个或多个标志(flags)，用以标明正则表达式的行为，正则表达式支持下列3个标志：</p>
<blockquote>
<ul>
<li>g：表示全局（global）模式，即模式将被应用于所有字符串，而非在发现第一个匹配项时立即停止；</li>
<li>i：表示不区分大小写（case-insensitive）模式，即在确定匹配项时忽略模式与字符串的大小写；</li>
<li>m：表示多行（multiline）模式，即在到达一行文本末尾时还会继续查找下一行中是否存在与模式匹配的项。</li>
</ul>
</blockquote>
<h1 id="正则表达式的元字符"><a href="#正则表达式的元字符" class="headerlink" title="正则表达式的元字符"></a>正则表达式的元字符</h1><h2 id="1"><a href="#1" class="headerlink" title="1. ()  []  {}"></a>1. ()  []  {}</h2><p>()：<strong>的作用是提取匹配的字符串</strong>。表达式中有几个()就会得到几个相应的匹配字符串。比如 (\s+) 表示连续空格的字符串。</p>
<p>[]：<strong>是定义匹配的字符范围</strong>。比如 [a-zA-Z0-9] 表示字符文本要匹配英文字符和数字。</p>
<p>{}：<strong>一般用来表示匹配的长度</strong>，比如 \d{3} 表示匹配三个数字，\d{1,3} 表示匹配1~3个数字，\d{3,} 表示匹配3个以上数字。</p>
<h2 id="2"><a href="#2" class="headerlink" title="2. ^  $"></a>2. ^  $</h2><p>^：<strong>匹配一个字符串的开头</strong>，比如(^a)就是匹配以字母a开头的字符串</p>
<p>\$：<strong>匹配一个字符串的结尾</strong>，比如(b$)就是匹配以字母b结尾的字符串</p>
<p>^ 还有另个一个作用就是取反，比如[^xyz]表示匹配的字符串不包含xyz<br><strong>注意：</strong><br>如果<strong>^ 出现在[ ]中一般表示取反</strong>，而出现在其他地方则是匹配字符串的开头。</p>
<h2 id="3-d-s-w"><a href="#3-d-s-w" class="headerlink" title="3. \d   \s   \w   ."></a>3. \d   \s   \w   .</h2><p>\d：匹配一个非负整数， 等价于 [0-9]</p>
<p>\s：匹配一个空白字符</p>
<p>\w：匹配一个英文字母或数字，等价于[0-9a-zA-Z]</p>
<p>. ：匹配除换行符以外的任意字符，等价于[^\n]</p>
<h2 id="4"><a href="#4" class="headerlink" title="4. *  +  ?"></a>4. *  +  ?</h2><p>* ：表示匹配前面元素0次或多次，比如 (\s*)就是匹配0个或多个空格</p>
<p>+ ：表示匹配前面元素1次或多次，比如 (\d+)就是匹配由至少1个整数组成的字符串</p>
<p>? ：表示匹配前面元素0次或1次，相当于{0,1} ，比如(\w?)就是匹配最多由1个字母或数字组成的字符串 </p>
<h2 id="5-1-1"><a href="#5-1-1" class="headerlink" title="5. $1  \1"></a>5. $1  \1</h2><p>\$1-\$9 存放着正则表达式中最近的9个正则表达式的提取的结果，这些结果按照子匹配的出现顺序依次排列。基本语法是：RegExp.$n ，这些属性是静态的，除了replace中的第二个参数可以省略 RegExp 之外，其他地方使用都要加上 RegExp。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用RegExp访问</span></span><br><span class="line">/(\d+)-(\d+)-(\d+)/.test(<span class="string">'2016-03-26'</span>)</span><br><span class="line"><span class="built_in">RegExp</span>.$<span class="number">1</span> <span class="comment">//2016</span></span><br><span class="line"><span class="built_in">RegExp</span>.$<span class="number">2</span> <span class="comment">//03</span></span><br><span class="line"><span class="built_in">RegExp</span>.$<span class="number">3</span> <span class="comment">//26</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//在replace中使用</span></span><br><span class="line"><span class="string">'2016-03-26'</span>.replace(<span class="regexp">/(\d+)-(\d+)-(\d+)/</span>,<span class="string">'$1年$2月$3日'</span>)</span><br><span class="line"><span class="comment">// 2016年03月26日</span></span><br></pre></td></tr></table></figure>
<p>\1  表示后向引用，是指在正则表达式中，从左往右数，第1个()中的内容，以此类推，\2表示第2个()，\0表示整个表达式。</p>
<p>其后面出现\1则是代表与第一个小括号中要匹配的内容相同<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//匹配日期格式，表达式中的\1代表重复(\-|\/|.)</span></span><br><span class="line"><span class="keyword">var</span> rgx = <span class="regexp">/\d&#123;4&#125;(\-|\/|.)\d&#123;1,2&#125;\1\d&#123;1,2&#125;/</span></span><br><span class="line"></span><br><span class="line">rgx.test(<span class="string">'2016-03-26'</span>) <span class="comment">//true</span></span><br><span class="line"></span><br><span class="line">rgx.test(<span class="string">'2016-03.26'</span>) <span class="comment">//false</span></span><br></pre></td></tr></table></figure></p>
<p><strong>两者的区别：</strong>\n只能用在表达式中，而$n只能用在表达式之外的地方</p>
<h1 id="6-RegExp-prototype-test-String-prototype-match"><a href="#6-RegExp-prototype-test-String-prototype-match" class="headerlink" title="6. RegExp.prototype.test()   String.prototype.match()"></a>6. RegExp.prototype.test()   String.prototype.match()</h1><p>test：用来检测字符串是否匹配某一个正则表达式，如果匹配就会返回true，反之则返回false<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">/\d+<span class="regexp">/.test('123'); /</span><span class="regexp">/true</span></span><br><span class="line"><span class="regexp">/</span>\d+<span class="regexp">/.test('abc'); /</span><span class="regexp">/false</span></span><br></pre></td></tr></table></figure></p>
<p>match：是获取正则匹配到的结果，以数组的形式返回<br>‘186a619b28’.match(/\d+/g); //[‘186’,’619’,’28’]</p>
<h1 id="7-String-prototype-replace"><a href="#7-String-prototype-replace" class="headerlink" title="7. String.prototype.replace()"></a>7. String.prototype.replace()</h1><p>replace 本身是JavaScript字符串对象的一个方法，它允许接收两个参数：<br><strong>str.replace([RegExp|String], [String|Function])</strong><br>参数1：可以是一个普通的字符串或是一个正则表达式<br>参数2：可以是一个普通的字符串或是一个回调函数</p>
<h2 id="7-1-实现字符串trim函数，去除字符串两边的空格"><a href="#7-1-实现字符串trim函数，去除字符串两边的空格" class="headerlink" title="7.1 实现字符串trim函数，去除字符串两边的空格"></a>7.1 实现字符串trim函数，去除字符串两边的空格</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">String</span>.prototype.trim = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">   <span class="comment">//方式一：将匹配到的每一个结果都用''替换</span></span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">this</span>.replace(<span class="regexp">/(^\s+)|(\s+$)/g</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">""</span>;</span><br><span class="line">   &#125;);</span><br><span class="line">   <span class="comment">//方式二</span></span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">this</span>.replace(<span class="regexp">/(^\s+)|(\s+$)/</span>,<span class="string">""</span>);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="7-2-提取浏览器url中的参数名和参数值"><a href="#7-2-提取浏览器url中的参数名和参数值" class="headerlink" title="7.2 提取浏览器url中的参数名和参数值"></a>7.2 提取浏览器url中的参数名和参数值</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getUrlParamObj</span>(<span class="params">url</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> obj = &#123;&#125;;</span><br><span class="line">  url.replace(<span class="regexp">/([^?&amp;=]+)=([^&amp;=]*)/gi</span>,<span class="function"><span class="keyword">function</span>(<span class="params">rs,$<span class="number">1</span>,$<span class="number">2</span></span>)</span>&#123;</span><br><span class="line">     obj[$<span class="number">1</span>] = $<span class="number">2</span>;</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> obj;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>作为replace方法第二个参数的替换函数，可以接受多个参数：</p>
<p>第一个参数是捕捉到的内容；<br>第二个参数是捕捉到的组匹配（有多少个组匹配，就有多少个对应的参数）；<br>此外，最后还可以添加两个参数，<br>倒数第二个参数是捕捉到的内容在整个字符串中的位置（比如从第五个位置开始）；<br>最后一个参数是原字符串。</p>
<h1 id="8-RegExp-prototype-exec"><a href="#8-RegExp-prototype-exec" class="headerlink" title="8. RegExp.prototype.exec()"></a>8. RegExp.prototype.exec()</h1><p>用来返回匹配结果，如果发现匹配，就返回一个数组，成员是匹配成功的子字符串，否则返回null。<br>exec方法的返回数组还包含以下两个属性：</p>
<blockquote>
<ul>
<li>input：整个原字符串</li>
<li>index：整个模式匹配成功的开始位置(从0开始计数)<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> r = <span class="regexp">/a(b+)a/</span>;</span><br><span class="line"><span class="keyword">var</span> arr = r.exec(<span class="string">'_abbba_aba_'</span>);</span><br><span class="line"></span><br><span class="line">arr <span class="comment">// ["abbba", "bbb"]</span></span><br><span class="line"></span><br><span class="line">arr.index <span class="comment">// 1</span></span><br><span class="line">arr.input <span class="comment">// "_abbba_aba_"</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
</blockquote>
<p>如果正则表达式加上g修饰符，则可以使用多次exec方法，下一次搜索的位置从上一次匹配成功结束的位置开始。利用g修饰符允许多次匹配的特点，可以用一个循环完成全部匹配。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/a/g</span>;</span><br><span class="line"><span class="keyword">var</span> str = <span class="string">'abc_abc_abc'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span>(<span class="literal">true</span>) &#123;</span><br><span class="line">  <span class="keyword">var</span> match = reg.exec(str);</span><br><span class="line">  <span class="keyword">if</span> (!match) <span class="keyword">break</span>;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'#'</span> + match.index + <span class="string">':'</span> + match[<span class="number">0</span>]);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// #0:a</span></span><br><span class="line"><span class="comment">// #4:a</span></span><br><span class="line"><span class="comment">// #8:a</span></span><br></pre></td></tr></table></figure></p>
<h1 id="9-String-prototype-search"><a href="#9-String-prototype-search" class="headerlink" title="9. String.prototype.search()"></a>9. String.prototype.search()</h1><p>字符串对象的search方法，返回第一个满足条件的匹配结果在整个字符串中的位置。如果没有任何匹配，则返回-1。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'_x_x'</span>.search(<span class="regexp">/x/</span>);</span><br><span class="line"><span class="comment">// 1</span></span><br></pre></td></tr></table></figure></p>
<h1 id="10-String-prototype-split"><a href="#10-String-prototype-split" class="headerlink" title="10. String.prototype.split()"></a>10. String.prototype.split()</h1><p>字符串对象的split方法按照正则规则分割字符串，返回一个由分割后的各个部分组成的数组。</p>
<p><strong>str.split(separator, [limit])</strong><br>第一个参数是正则表达式，表示分隔规则，第二个参数是返回数组的最大成员数。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 非正则分隔</span></span><br><span class="line"><span class="string">'a,  b,c, d'</span>.split(<span class="string">','</span>)</span><br><span class="line"><span class="comment">// [ 'a', '  b', 'c', ' d' ]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 正则分隔，去除多余的空格</span></span><br><span class="line"><span class="string">'a,  b,c, d'</span>.split(<span class="regexp">/, */</span>)</span><br><span class="line"><span class="comment">// [ 'a', 'b', 'c', 'd' ]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 指定返回数组的最大成员</span></span><br><span class="line"><span class="string">'a,  b,c, d'</span>.split(<span class="regexp">/, */</span>, <span class="number">2</span>)</span><br><span class="line">[ <span class="string">'a'</span>, <span class="string">'b'</span> ]</span><br></pre></td></tr></table></figure></p>
<h1 id="11-贪婪模式"><a href="#11-贪婪模式" class="headerlink" title="11. 贪婪模式"></a>11. 贪婪模式</h1><p>将贪婪模式改为非贪婪模式，可以在量词符后面加一个问号<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> s = <span class="string">'aaa'</span>;</span><br><span class="line">s.match(<span class="regexp">/a+?/</span>) <span class="comment">// ["a"]</span></span><br></pre></td></tr></table></figure></p>
<blockquote>
<ul>
<li>*?：表示某个模式出现0次或多次，匹配时采用非贪婪模式。</li>
<li>+?：表示某个模式出现1次或多次，匹配时采用非贪婪模式。</li>
</ul>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/reimupage/tags/JavaScript/" rel="tag"># JavaScript</a>
          
            <a href="/reimupage/tags/RegExp/" rel="tag"># RegExp</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/reimupage/2018/04/29/Array对象/" rel="next" title="Array对象 笔记">
                <i class="fa fa-chevron-left"></i> Array对象 笔记
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/reimupage/2018/05/07/String对象/" rel="prev" title="String对象 笔记">
                String对象 笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/reimupage/images/avatar.gif"
                alt="Reimu" />
            
              <p class="site-author-name" itemprop="name">Reimu</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/reimupage/archives/">
              
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#正则表达式-笔记"><span class="nav-number">1.</span> <span class="nav-text">正则表达式 笔记</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">2.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#正文"><span class="nav-number">3.</span> <span class="nav-text">正文</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#正则表达式的元字符"><span class="nav-number">4.</span> <span class="nav-text">正则表达式的元字符</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1"><span class="nav-number">4.1.</span> <span class="nav-text">1. ()  []  {}</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2"><span class="nav-number">4.2.</span> <span class="nav-text">2. ^  $</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-d-s-w"><span class="nav-number">4.3.</span> <span class="nav-text">3. \d   \s   \w   .</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4"><span class="nav-number">4.4.</span> <span class="nav-text">4. *  +  ?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-1-1"><span class="nav-number">4.5.</span> <span class="nav-text">5. $1  \1</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#6-RegExp-prototype-test-String-prototype-match"><span class="nav-number">5.</span> <span class="nav-text">6. RegExp.prototype.test()   String.prototype.match()</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#7-String-prototype-replace"><span class="nav-number">6.</span> <span class="nav-text">7. String.prototype.replace()</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#7-1-实现字符串trim函数，去除字符串两边的空格"><span class="nav-number">6.1.</span> <span class="nav-text">7.1 实现字符串trim函数，去除字符串两边的空格</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-2-提取浏览器url中的参数名和参数值"><span class="nav-number">6.2.</span> <span class="nav-text">7.2 提取浏览器url中的参数名和参数值</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#8-RegExp-prototype-exec"><span class="nav-number">7.</span> <span class="nav-text">8. RegExp.prototype.exec()</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#9-String-prototype-search"><span class="nav-number">8.</span> <span class="nav-text">9. String.prototype.search()</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#10-String-prototype-split"><span class="nav-number">9.</span> <span class="nav-text">10. String.prototype.split()</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#11-贪婪模式"><span class="nav-number">10.</span> <span class="nav-text">11. 贪婪模式</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Reimu</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/reimupage/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/reimupage/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/reimupage/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/reimupage/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/reimupage/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/reimupage/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/reimupage/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/reimupage/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/reimupage/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/reimupage/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/reimupage/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/reimupage/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/reimupage/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/reimupage/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
